package com.deyuanyun.pic.settings.controller.prvlg;

import com.deyuanyun.pic.common.util.poi.ExcelUtil;
import com.deyuanyun.pic.common.util.web.WebUtil;
import com.deyuanyun.pic.common.validator.imlclass.BeanValidateUtil;
import com.deyuanyun.pic.common.validator.imlclass.VResult;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.deyuanyun.pic.settings.util.DownExcelUtil;
import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.deyuanyun.pic.common.dto.PageJsonBean;
import com.deyuanyun.pic.common.tool.StaticParam;
import com.deyuanyun.pic.common.util.FileUtils;
import com.deyuanyun.pic.common.util.MyCollectionUtil;
import com.deyuanyun.pic.common.util.ObjectUtil;
import com.deyuanyun.pic.common.util.RequestUtil;
import com.deyuanyun.pic.common.util.ajax.AjaxResponse;
import com.deyuanyun.pic.common.util.ajax.AjaxSupport;
import com.deyuanyun.pic.common.util.jxl.ExcelUtils;
import com.deyuanyun.pic.common.util.poi.ReadExcel;
import com.deyuanyun.pic.common.util.poi.WriteExcel;
import com.deyuanyun.pic.common.util.web.Asserts;
import com.deyuanyun.pic.common.util.web.RequestResponseContext;
import com.deyuanyun.pic.common.validator.imlclass.BeanValidateUtil;
import com.deyuanyun.pic.common.validator.imlclass.VResult;
import com.deyuanyun.pic.settings.controller.dto.prvlg.UserExportVO;
import com.deyuanyun.pic.settings.controller.dto.prvlg.UserVO;
import com.deyuanyun.pic.settings.domain.org.OrgInfo;
import com.deyuanyun.pic.settings.domain.prvlg.UserImpVO;
import com.deyuanyun.pic.settings.service.prvlg.UserService;
import com.github.pagehelper.PageHelper;

@Controller
@RequestMapping("/settings/user")
public class UserController {
	static Logger logger = Logger.getLogger(UserController.class);
	@Resource
	private UserService userService;

	@RequestMapping("/testMgr")
	public String settings(Model model) {
		return "/settings/paramMgr";
	}

	@RequestMapping("/toParamDetails")
	public String paramDetails() {
		return "/settings/paramDetails";
	}

	@RequestMapping("/toTestCode")
	public String testCode(Model model) {
		return "/settings/testCode";
	}

	/**************** ADD BY TKC **********************/
	/**
	 * 跳转用户管理主界面
	 * 
	 * @return
	 */
	@RequestMapping("/getUserManagerIndex.html")
	public ModelAndView getUserManagerIndex() {
		ModelAndView mv = new ModelAndView();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("locked", null);
		List<UserVO> main = userService.getUserManagerIndex(map);
		List<OrgInfo> companyList = userService.selectAllCompany();
		mv.addObject("main", main);
		mv.addObject("companyList", companyList);
		mv.setViewName("/settings/prvlg/userManager");
		return mv;
	}

	/**
	 * 查询用户
	 * 
	 * @param uv
	 */
	@RequestMapping("/searchUser.json")
	@ResponseBody
	public void searchUser(UserVO uv) {
		String username = "";
		String company = "";
		String department = "";
		if (!StringUtils.isEmpty(uv.getUsername())) {
			username = uv.getUsername();
		}
		if (!StringUtils.isEmpty(uv.getCompanyId())) {
			company = uv.getCompanyId();
		}
		if (!StringUtils.isEmpty(uv.getDepartmentId())) {
			department = uv.getDepartmentId();
		}
		String isAuthorize = uv.getIsAuthorize();
		List<UserVO> list = userService.searchUser(username, company, department, isAuthorize);
		
		AjaxSupport.sendSuccessText("", list);
	}

	
	@RequestMapping("/findList.json")
	@ResponseBody
	public void findList(HttpServletRequest request) {
		PageJsonBean jsonBean = new PageJsonBean(false);
		PageHelper.startPage(1,10000);
		HashMap param= RequestUtil.parseRequestParamToHashMap(request);
		List<UserVO> list = userService.findList(param);
		jsonBean.setList(list);
		AjaxSupport.sendSuccessText("", jsonBean);
	}
	
	/**
	 * 平台导出
	 * 
	 * @param response
	 * @param uv
	 */
	@RequestMapping("/exportData.html")
	public void exportData(HttpServletResponse response, UserVO uv) throws IOException {
		List<String[]> result = userService.exportData(uv);
		String filePath = "/template/excl/user/user_templet.xls";
	//	InputStream inputStream = this.getClass().getResourceAsStream("/template/excl/user/user_templet.xls");
//		int[] lineStart = new int[] { 1 };
//		ExcelUtils.jxlExportExcel(inputStream, lineStart, "用户列表", list, response);
		Workbook externalDefect = ExcelUtil.initWorkbook(filePath, result, 1);
		DownExcelUtil.fillWorkbookHead(externalDefect);
		WebUtil.setDownHeader("用户列表信息.xls");
		externalDefect.write(response.getOutputStream());
	}

	/**
	 * 查询所有的公司
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping("/ajaxGetCompany.json")
	@ResponseBody
	public void ajaxGetCompany() {
		List<OrgInfo> companyList = userService.selectAllCompany();
		AjaxSupport.sendSuccessText("r", companyList);
	}

	/**
	 * 查询公司的部门
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping("/ajaxGetDepartment.json")
	@ResponseBody
	public void ajaxGetDepartment(String companyId) {
		List<OrgInfo> departmentList = userService.selectDepartmentByCompanyId(companyId);
		AjaxSupport.sendSuccessText("r", departmentList);
	}

	/**
	 * 查询部门的职位
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping("/ajaxGetPosition.json")
	@ResponseBody
	public void ajaxGetPosition(String departmentId) {
		List<OrgInfo> positionList = userService.selectPositionByDepartmentId(departmentId);
		AjaxSupport.sendSuccessText("r", positionList);
	}

	/**
	 * 保存用户信息
	 * 
	 * @param uv
	 * @return
	 */
	@RequestMapping("/saveUser.json")
	@ResponseBody
	public void saveUser(UserVO uv) throws Exception {
		Asserts.assertTrue(!StringUtils.isEmpty(uv.getUsername()), "请输入用户名称");
//		Asserts.assertTrue(!StringUtils.isEmpty(uv.getMobile()), "请输入手机号码");
//		Asserts.assertTrue(!StringUtils.isEmpty(uv.getEmail()), "请输入邮箱地址");
		Asserts.assertTrue(!StringUtils.isEmpty(uv.getRealName()), "请输入姓名");
		Asserts.assertTrue(!StringUtils.isEmpty(uv.getSex()), "请选择性别");
//		Asserts.assertTrue(!StringUtils.isEmpty(uv.getCode()), "请输入工号");
		Asserts.assertTrue(!StringUtils.isEmpty(uv.getCompanyId()), "请选择公司");
		Asserts.assertTrue(!StringUtils.isEmpty(uv.getDepartmentId()), "请选择部门");
		// Asserts.assertTrue(!StringUtils.isEmpty(uv.getPositionId()),
		// "请选择职位");
		Asserts.assertTrue(!StringUtils.isEmpty(uv.getState()), "请设置状态");
		// 用户名称
		String username = uv.getUsername();
		// 手机号码
		String moblie = uv.getMobile();
		// 邮箱
		String email = uv.getEmail();
		// 姓名
		String realName = uv.getRealName();
		// 性别
		String sex = uv.getSex();
		// 工号
		String code = uv.getCode();
		// 公司
		String companyId = uv.getCompanyId();
		// 部门
		String departmentId = uv.getDepartmentId();
		// 职位
		String positionId = uv.getPositionId();
		// 状态
		String state = uv.getState();
		// 备注
		String remark = uv.getRemark();
		// 用户Id
		String userId = uv.getId();
		int i = userService.save(username, moblie, email, realName, sex, code, companyId, departmentId, positionId,
				state, remark, userId);
		if (i > 0) {
			// ajax成功返回数据
			AjaxSupport.sendSuccessText("msgCode", "1");
		}
	}

	/**
	 * 点击列表状态栏，改变用户状态
	 * 
	 * @param uv
	 * @throws Exception
	 */
	@RequestMapping("/changeState.json")
	@ResponseBody
	public void changeState(UserVO uv) throws Exception {
		Asserts.assertTrue(!StringUtils.isEmpty(uv.getId()), "数据异常，请刷新页面重试");
		Asserts.assertTrue(!StringUtils.isEmpty(uv.getState()), "数据异常，请刷新页面重试");
		String userId = uv.getId();
		String state = uv.getState();
		int i = userService.changeState(userId, state);
		if (i > 0) {
			AjaxSupport.sendSuccessText("", "1");
		}
	}

	/**
	 * 点击授权 ，加载基本信息
	 * 
	 * @param id
	 */
	@RequestMapping("/userAuthorize.json")
	@ResponseBody
	public void userAuthorize(String id) {
		Asserts.assertTrue(!StringUtils.isEmpty(id), "请点击需要授权的数据");
		Map<String, Object> map = new HashMap<String, Object>();
		map = userService.userAuthorize(id);
		AjaxSupport.sendSuccessText("", map);
	}

	/**
	 * 保存用户授权信息
	 * 
	 * @param id
	 * @param str
	 */
	@RequestMapping("/saveAuthorize.json")
	@ResponseBody
	public void saveAuthorize(String id, String str) {
		String[] data = str.split(",");
		if (data.length > 0 && !StringUtils.isEmpty(id)) {
			int i = userService.saveAuthorize(id, data);
			AjaxSupport.sendSuccessText("", i);
		}
	}

	/**
	 * 删除用户
	 * 
	 * @param idStr
	 */
	@RequestMapping("/deleteData.json")
	@ResponseBody
	public void deleteData(String idStr) {
		Asserts.assertTrue(!StringUtils.isEmpty(idStr), "请勾选需要删除的数据");
		int count = userService.deleteData(idStr);
		AjaxSupport.sendSuccessText("", count);
	}

	/**
	 * 启用或停用用户
	 * 
	 * @param idStr
	 * @param opt
	 */
	@RequestMapping("/dataOnOrOff.json")
	@ResponseBody
	public void dataOnOrOff(String idStr, String opt) {
		Asserts.assertTrue(!StringUtils.isEmpty(idStr), "请勾选需要操作的数据");
		Asserts.assertTrue(!StringUtils.isEmpty(opt), "数据异常，请刷新页面重试");
		int count = userService.dataOnOrOff(idStr, opt);
		AjaxSupport.sendSuccessText("", count);
	}

	/**
	 * 重置密码为111111
	 * 
	 * @param idStr
	 */
	@RequestMapping("/resetPwd.json")
	@ResponseBody
	public void resetPwd(String idStr) {
		Asserts.assertTrue(!StringUtils.isEmpty(idStr), "请勾选需要操作的数据");
		int count = userService.resetPwd(idStr);
		AjaxSupport.sendSuccessText("", count);
	}

	/**********************************
	 * 独立系统独自使用的**开始
	 ***********************************/
	/**
	 * 链接权限管理
	 * 
	 * @return
	 */
	@RequestMapping("/authorizeManager.html")
	public ModelAndView authorizeManager() {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/settings/prvlg/authorizeManager");
		return mv;
	}

	/**
	 * 用户列表
	 * 
	 * @param uv
	 */
	@RequestMapping("/userList.json")
	@ResponseBody
	public void userList(UserVO uv) {
		PageJsonBean jsonBean = new PageJsonBean();
		String username = "";
		String company = "";
		String department = "";
		String isAuthorize = "";
		if (!StringUtils.isEmpty(uv.getUsername())) {
			username = uv.getUsername();
		}
		if (!StringUtils.isEmpty(uv.getCompanyId())) {
			company = uv.getCompanyId();
		}
		if (!StringUtils.isEmpty(uv.getDepartmentId())) {
			department = uv.getDepartmentId();
		}
		if (!StringUtils.isEmpty(uv.getIsAuthorize())) {
			isAuthorize = uv.getIsAuthorize();
		} else {
			isAuthorize = "0";
		}
		List<UserVO> list = userService.searchUser(username, company, department, isAuthorize);
		jsonBean.setList(list);
		AjaxSupport.sendSuccessText("", jsonBean);
	}

	/**
	 * 导出用户 独立清管
	 * 
	 * @param response
	 * @param uv
	 */
	@RequestMapping("/exportUser.html")
	@ResponseBody
	public void exportUser(HttpServletResponse response, UserVO uv) throws Exception {
		String templateName = "out/user_out_templet.xls";
		Workbook workbook = ReadExcel.readExcelTemplate(templateName);
		String[] cnName = ReadExcel.cnNameMap.get(templateName);
		if (cnName != null && cnName.length > 0 && org.apache.commons.lang.StringUtils.isNotBlank(cnName[0])) {
			HttpServletRequest request = RequestResponseContext.getRequest();
			String suff = FileUtils.getNameSuff(templateName);
			templateName = FileUtils.processFileName(request, cnName[0]) + suff;
		}
		response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet ; charset=utf-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Content-Disposition", "attachment;filename=" + StringUtils.replace(templateName, "/", "-"));
		List<UserExportVO> list = userService.exportUser(uv);
		Workbook workbookFinal = WriteExcel.writeExcel(workbook, list, 1, null);
		ServletOutputStream outputStream = null;
		try {
			outputStream = response.getOutputStream();
			workbookFinal.write(outputStream);
			outputStream.flush();
		} catch (IOException e) {
			logger.error("", e);
		} finally {
			if (outputStream != null) {
				outputStream.close();
			}
		}
		return;
	}

	/**
	 * 独立清管用户导入
	 * 
	 * @param multipartFiles
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("importUser.json")
	@ResponseBody
	public void importUser(@RequestParam("file") MultipartFile[] multipartFiles, HttpServletResponse response)
			throws Exception {
		Asserts.assertTrue(!ObjectUtil.isEmptyAll(multipartFiles), "附件不能为空");
		List<UserImpVO> xx = ReadExcel.readExcle(UserImpVO.class, multipartFiles[0].getInputStream(), 1, "10");
		List<UserImpVO> finalInfo = MyCollectionUtil.removeLastEmpty(xx);
		VResult b = BeanValidateUtil.vali2(finalInfo, 1 + "");
		if (b.isRelult()) {
			userService.insertImpUser(finalInfo);
			AjaxResponse.sendText(response, StaticParam.UPLOAD_FILE_SUCCESS);
		} else {
			String[] titleArr = ReadExcel.getTitle(multipartFiles[0], "in/user_in_templet.xls");
			String m = b.getAllString(titleArr);
			response.setStatus(503);
			AjaxResponse.sendText(response, StaticParam.getUploadFileFailMessage(m));
		}
		return;
	}

	/**********************************
	 * 独立系统独自使用的**结束
	 ***********************************/
}
